import 'dart:async';

import 'package:flutter/services.dart';
import 'package:huawei_login/huawei_login.dart';

const _kMessageChannel = 'com.flutterOhos/sign_in_with_huawei';

class HuaweiLogin {
  HuaweiLogin._();

  static final HuaweiLogin _instance = HuaweiLogin._();

  static HuaweiLogin get instance => _instance;

  final _channel = const MethodChannel(_kMessageChannel);

  /// 华为账号登录(获取 UnionID/OpenID)
  Future<HuaweiAuthByIdResponse> authById({
    bool forceLogin = true,
    String? state,
    String? nonce,
    IdTokenSignAlgorithm idTokenAlg = IdTokenSignAlgorithm.PS256,
  }) async {
    final result = await _channel.invokeMethod(
      'authById',
      <String, dynamic>{
        'forceLogin': forceLogin,
        if (state != null) 'state': state,
        if (nonce != null) 'nonce': nonce,
        'idTokenAlg': idTokenAlg.value,
      },
    );
    final response = HuaweiAuthByIdResponse.fromMap(result);
    return response;
  }

  Future<HuaweiAuthByIdResponse> authByQuickLogin() async {
    final result = await _channel.invokeMethod('authByQuickLogin');
    final response = HuaweiAuthByIdResponse.fromMap(result);
    return response;
  }

  Future<HuaweiAuthByIdResponse> authByGetPhone() async {
    final result = await _channel.invokeMethod('authByGetPhone');
    final response = HuaweiAuthByIdResponse.fromMap(result);
    return response;
  }
}

enum IdTokenSignAlgorithm {
  // ignore: constant_identifier_names
  PS256,
  // ignore: constant_identifier_names
  RS256;

  String get value {
    switch (this) {
      case IdTokenSignAlgorithm.PS256:
        return 'PS256';
      case IdTokenSignAlgorithm.RS256:
        return 'RS256';
    }
  }
}
